package com.yue92.datalife.helper;

import com.yue92.datalife.model.Record;
import com.yue92.datalife.response.AnalysisLineSingleRes;
import com.yue92.datalife.response.RecordRes;
import com.yue92.datalife.service.IAnalysisService;
import com.yue92.datalife.service.ICustomExecutor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author mundo.wang on 2020/9/9
 */
@Component
public class AnalysisHelper {

    @Autowired
    private IAnalysisService analysisService;

    @Autowired
    private ICustomExecutor executor;

    @SneakyThrows
    public AnalysisLineSingleRes index(Record record, LocalDate date, Boolean cumulate) {

        LocalDate yearLast = LocalDate.of(date.minusYears(1).getYear(), 1, 1);
        Future<IAnalysisService.AnalysisResult> futureLast = executor.submit(() -> analysisService.getData(yearLast, record, cumulate));

        LocalDate yearNow = LocalDate.of(date.getYear(), 1, 1);
        Future<IAnalysisService.AnalysisResult> futureNow = executor.submit(() -> analysisService.getData(yearNow, record, cumulate));

        IAnalysisService.AnalysisResult resultLast = futureLast.get();
        IAnalysisService.AnalysisResult resultNow = futureNow.get();

        List<Integer> all = new ArrayList<>();
        all.addAll(resultLast.getSeriesData());
        all.addAll(resultNow.getSeriesData());

        int max = all.stream().mapToInt(value -> value == null ? 0 : value).max().getAsInt();

        return AnalysisLineSingleRes
                .builder()
                .recordDate(date.toString())
                .record(RecordRes.builder()
                        .id(record.getId())
                        .name(record.getName())
                        .allowCumulate(record.getAllowCumulate())
                        .build())
                .girdX(analysisService.getGirdX(max))
                .xAxisData(Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
                .seriesNameLast(resultLast.getSeriesName())
                .seriesDataLast(resultLast.getSeriesData())
                .seriesNameNow(resultNow.getSeriesName())
                .seriesDataNow(resultNow.getSeriesData())
                .build();
    }

}
